/*

Copyright 2009 Nicola Dal Pont

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Version ${MAJOR_VERSION}.${MINOR_VERSION}${BETA_MARK} Build ${BUILD_NUMBER}

*/

package com.astoolkit.workflow
{
	import com.astoolkit.workflow.api.*;
	import com.astoolkit.workflow.constant.EMPTY_PIPELINE;
	import com.astoolkit.workflow.constant.EmptyPipelinePolicy;
	import com.astoolkit.workflow.constant.FailurePolicy;
	import com.astoolkit.workflow.constant.Feed;
	import com.astoolkit.workflow.constant.Flow;
	import com.astoolkit.workflow.constant.Iterate;
	import com.astoolkit.workflow.constant.TaskStatus;
	import com.astoolkit.workflow.constant.UNDEFINED;
	
	import flash.utils.getQualifiedClassName;
	
	import mx.collections.IList;
	import mx.core.IFactory;
	import mx.logging.ILogger;
	import mx.logging.Log;
	import mx.rpc.Fault;
	
    [DefaultProperty("children")]
	public class SyncWorkflow extends AbstractWorkflow implements IWorkflow, IRepeater
	{
        private static const LOGGER : ILogger = 
            Log.getLogger( getQualifiedClassName( SyncWorkflow ).replace(/:+/g, "." ) );

        private var _wasAborted : Boolean = false;
		
        private var _feedWasSet : Boolean;

		public function SyncWorkflow() 
		{
			super();
			_childrenDelegate = createDelegate();
			_flow = Flow.SERIAL
		}
		
		override public function initialize():void
		{
			super.initialize();
            if( runtimeTasks.length > 0 )
            {
                for each( var task : IWorkflowTask in runtimeTasks )
                {						
                    task.delegate = _childrenDelegate;
                    task.context = _context;
                    task.initialize();
                }
            }
            
		}
		
		override public function get async() : Boolean
		{
			return false;
		}
		
		override public function prepare():void
		{
			_wasAborted = false;
			if( parent )
				_pipelineData = UNDEFINED;
            _status = TaskStatus.IDLE;
		}
		
		[Inspectable(defaultValue="serial", enumeration="serial,none")]
		override public function set flow(inFlow:String):void
		{
			_flow = inFlow;
		}
		
		override public function begin():void
		{
			_subPipelineData = UNDEFINED;
			if(!_delegate)
				_delegate = createDelegate();
            if( !_parent )
            {
                _context.init();
                //retriggering task input setter
                //to make sure $.data is set even when taskInput is set
                //before running the workflow
                taskInput = _pipelineData;
				initialize();
				prepare();
            }
            super.begin();
            if( _dataProvider )
                _iterate = Iterate.DATA;
            if( _iterate == Iterate.DATA )
            {
                _currentDataIndex = -1;
                if( !_feedWasSet )
                    _feed = Feed.CURRENT_DATA;
                if( !dataProvider || dataProvider.length == 0)
                {
                    if( filteredPipelineData is IList && filteredPipelineData.length > 0 )
                    {
                        _dataProvider = IList( filteredPipelineData );
                        _clearDataProviderOnComplete = true;				
                    }
                }
                
                if( dataProvider != null && dataProvider.length > 0 )
                {
                    try
                    {
                        _currentDataIndex ++;
                        currentData = dataProvider.getItemAt( _currentDataIndex );
                    }
                    catch( e : Error )
                    {
                        fail( e.getStackTrace() );
                        return;
                    }
                }
                else
                {
                    LOGGER.info( "Workflow \"" + description + "\" completes with no data");
                    complete();
                    return;
                }
            }
			if( !runtimeTasks || runtimeTasks.length == 0 )
			{
				complete();
				return;
			}
                
            var iterateAgain : Boolean = true;
            do
            {
                nextData();
    			iterateAgain = runIteration();
            }
                while( _iterate != null && 
                    iterateAgain &&
                    !_wasAborted &&
                    ( _iterate == Iterate.LOOP || 
                        _currentDataIndex < dataProvider.length -1 ) );
			complete();
			
		}
		
        private function runIteration() : Boolean
        {

            for each( var task : IWorkflowTask in runtimeTasks )
            {
                if( _wasAborted )
                {
                    return false;
                }
                if( task.enabled && ( task.emptyPipelinePolicy != EmptyPipelinePolicy.SKIP || _subPipelineData != EMPTY_PIPELINE ) )
                {
                    try
                    {
                        setSubtaskPipelineData( task );
                        task.begin();
                    }
                    catch( e : Error )
                    {
                        if( task.failurePolicy == FailurePolicy.ABORT )
                        {
                            fail( e.getStackTrace() );
                            return false;
                        }
                    }
                }
            }           
            return true;
        }
        
		override protected function complete() : void
		{
            super.complete();
			if( _feed == Feed.PIPELINE || _feed == Feed.CURRENT_DATA )
				_pipelineData = _subPipelineData;
			_delegate.onComplete( this );
            if( !_parent )
                cleanUp();
		}
		
		override public function abort():void
		{
			_wasAborted = true;
		}
		
		//============================ DELEGATE =============================
		
		override protected function createDelegate() : IWorkflowDelegate
		{
			var delegate : IWorkflowDelegate = new DefaultWorkflowDelegate();
			delegate.onAbort = onSubtaskAbort;
			//delegate.onInitialize = onSubtaskInitialized;
			//delegate.onPrepare = onSubtaskPrepared;
			delegate.onBegin = onSubtaskBegin;
			delegate.onComplete = onSubtaskCompleted;
			delegate.onFault = onSubtaskFault
			delegate.onProgress = onSubtaskProgress;
			//delegate.onResume = onSubtaskResumed;
			//delegate.onSuspend = onSubtaskSuspended;
			delegate.onWarning = onSubtaskWarning;
			return delegate;
		}
		
		protected function onSubtaskBegin(inTask:IWorkflowTask):void
		{
			dispatchTaskEvent( WorkflowEvent.STARTED, inTask );
		}
		
		protected function onSubtaskProgress(inTask:IWorkflowTask):void
		{
			dispatchTaskEvent( WorkflowEvent.STARTED, inTask );
		}
		
		protected function onSubtaskFault(inTask:IWorkflowTask, inMessage:String, inFault:Fault):void
		{
			dispatchTaskEvent( WorkflowEvent.FAULT, inTask );
			
		}
		
		protected function onSubtaskAbort(inTask:IWorkflowTask, inMessage:String):void
		{
			dispatchTaskEvent( WorkflowEvent.ABORTED, inTask );
			
		}
		
		protected function onSubtaskWarning(inTask:IWorkflowTask, inMessage:String, inError:Fault):void
		{
			dispatchTaskEvent( WorkflowEvent.WARNING, inTask );
			
		}
		protected function onSubtaskCompleted( inTask : IWorkflowTask ) : void
		{
			dispatchTaskEvent( WorkflowEvent.COMPLETED, inTask );
			_subPipelineData = inTask.taskOutput;
		}
		
		
		
	}
}